package com.decheng.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;


/**
 * @Author 孔德成
 * @Slogan 致敬大师，致敬未来的你
 */
public class JDBCUtil {

    // 只创建一次数据源
    private static DataSource dataSource;

    static {
        Properties pro = new Properties();
        Connection conn = null;
        try {
            pro.load(JDBCUtil.class.getClassLoader().getResourceAsStream("druid.properties"));
            dataSource = DruidDataSourceFactory.createDataSource(pro);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取连接
     *
     * @return
     */
    public static Connection getConnection() throws SQLException {

        // 1. 读取配置信息
        String url = "jdbc:mysql://localhost:3306/book_shop";
        String user = "root";
        String password = "123456";
        String driverClass = "com.mysql.jdbc.Driver";

        // 2. 加载驱动
        try {
            Class.forName(driverClass);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        // 3. 获取连接
        return DriverManager.getConnection(url, user, password);
    }

    /**
     * @return
     * @throws SQLException 将异常抛给调用者，该层不处理异常
     */
    public static Connection getConnectionWithDruid() throws SQLException {
        return dataSource.getConnection();
    }

    /**
     * 释放资源
     *
     * @param connection
     */
    public static void closeResource(Connection connection) {

        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }


    }
}
